import * as vscode from 'vscode'
import * as fs from 'fs'
import * as path from 'path'
import { JutroConfig } from '../types'

import scssTml from '../tmpl/page.module.scss.tmpl'
import jsxTml from '../tmpl/page.jsx.tmpl'
import metadataTml from '../tmpl/page.metadata.json5.tmpl'
import msgTml from '../tmpl/page.messages.tmpl'

const pageTemplatFiles = [
  {
    generator: scssTml,
    ext: '.module.scss',
  },
  {
    generator: jsxTml,
    ext: '.jsx',
  },
  {
    generator: msgTml,
    ext: '.messages.js',
  },
  {
    generator: metadataTml,
    ext: '.metadata.json5',
  },
]

export default function getCreatePageCmd(config: JutroConfig) {
  return vscode.commands.registerCommand('jutror.createPage', async (param) => {
    const loc = param.fsPath

    if (!loc) return

    const inputName = await vscode.window.showInputBox({
      prompt: 'Please enter your page/component name',
      placeHolder:
        'Use camel case format, eg. VehicleDetail, ClaimInfo, and etc.',
    })
    if (!inputName) return

    let count = 0
    const basePath = `${loc}/${inputName}`
    fs.mkdirSync(basePath)
    pageTemplatFiles.forEach((item) => {
      try {
        const fileFWithPath = `${basePath}/${inputName}${item.ext}`
        const { version, schemaLocation } = config.jutro!;

        const pathToSchema = path.relative(loc, schemaLocation).replace(/\\/g, '/');

        const jutro = {
          version, 
          // because the created files are one level down so we add another level to leverage this
          pathToSchema: '../' + pathToSchema
        }

        fs.writeFileSync(
          fileFWithPath,
          item.generator(inputName, config.appPrefix || 'app', jutro)
        )
        count++
      } catch (error) {
        vscode.window.showErrorMessage(
          `Error creating file: ${inputName}${item.ext}. ${error}`
        )
      }
    })
    if (count === 4) {
      vscode.window.showInformationMessage('page files created!')
      vscode.window.showTextDocument(
        vscode.Uri.file(`${basePath}/${inputName}.jsx`),
        {
          preview: false,
        }
      )
    }
  })
}
